﻿/***************************************************************************
 创建者: 华磊
 开始时间: 2019.9.20
 copyright: (C) 华友高科
 ***************************************************************************/
#include "mainwindowfleet.h"

#include "global.h"

#include "mapeditwindow.h"
#include "monitordockblock.h"
#include "monitordockmaptree.h"
#include "monitordockproperty.h"
#include "monitordockview.h"
#include <QAction>
#include "mainwindowfleettest.h"
#include "mainwindowtestmanage.h"
#include "mapfileparse.h"
#include "../CommunicateDelegate/communicatenormaldelegate.h"
#include "../CommunicateDelegate/globaldata.h"
#include "../WindowShowManage/windowshowmanage.h"

extern WindowShowManage *g_windowShowManage;

MainWindowTestManage *g_fleetTestManagementWindow;

//extern MainWindowFleetTest* g_fleetTestWindow;
extern MainWindowTestManage *g_fleetTestManagementWindow;
extern double g_itemDisplayRatio;

MainWindowFleet::MainWindowFleet(CommunicateNormalDelegate *communicateNormalIn,
                                 GlobalData *globalDataIn, QWidget *parent) : QMainWindow(parent),
    dock_user_manage(nullptr),
    dock_agv_manage(nullptr),
    dock_user_log(nullptr),
    editWindow(nullptr),
    dock_task(nullptr),
    oneMap(g_onemap.clone())
{
    communicateNormal=communicateNormalIn;
    globalData=globalDataIn;
    //载入配置文件
    configure.load();

    //初始化到服务器的链接
//    msgCenter.init();
    msgCenter.setLoginMode(E_LOGIN_MODE_MONITOR);
//    msgCenter.mapLoad();
    setWindowTitle("调度客户端－主界面");
    createActions();
    createStatusBar();
//    fleetTestWindow = new MainWindowFleetTest();
//    fleetTestWindow = g_fleetTestWindow;
//    fleetTestWindow->hide();

    g_fleetTestManagementWindow= new MainWindowTestManage(this);
    fleetTestManagementWindow=g_fleetTestManagementWindow;
    fleetTestManagementWindow->hide();
//    Qt::WindowFlags flags = this->windowFlags();
//    fleetTestManagementWindow->setWindowFlags(flags | Qt::CustomizeWindowHint | Qt::WindowStaysOnTopHint);

    init();
}

void MainWindowFleet::init()
{
    connect(&msgCenter,SIGNAL(sig_connection_connected()),this,SLOT(onServerConnect()));
    connect(&msgCenter,SIGNAL(sig_connection_disconnected()),this,SLOT(onServerDisconnect()));
    connect(&msgCenter,SIGNAL(sig_connection_conntectting()),this,SLOT(onServerConnectting()));

    connect(&msgCenter,SIGNAL(sendRequestFail()),this,SLOT(onSendFail()));
    connect(&msgCenter,SIGNAL(waitResponseTimeOut()),this,SLOT(onWaitResponseTimeOut()));
    connect(&msgCenter,SIGNAL(tip(QString)),this,SLOT(onTip(QString)));
    connect(&msgCenter,SIGNAL(err(int,QString)),this,SLOT(onErr(int,QString)));
    connect(&msgCenter,SIGNAL(sendNewRequest()),this,SLOT(onNewRequest()));
    connect(&msgCenter,SIGNAL(loginSuccess(int)),this,SLOT(updateCurrentUserInfo()));
    connect(&msgCenter,SIGNAL(mapGetSuccess()),this,SLOT(onMapLoad()));

    //connect(dockMapTree,SIGNAL(sig_addFloor(MapFloor*)),dockView,SLOT(slot_addFloor(MapFloor*)));
    connect(dockMapTree,SIGNAL(sig_chooseSpirit(MapSpirit*)),dockProperty,SLOT(slot_showSpirit(MapSpirit*)));
    connect(dockMapTree,SIGNAL(sig_chooseSpirit(MapSpirit*)),dockView,SLOT(slot_selectChanged(MapSpirit *)));

    //connect(dockView,SIGNAL(sig_currentMousePos(QPointF)),this,SLOT(slot_currentMousePos(QPointF)));
    //connect(dockView,SIGNAL(sig_cancelTool()),this,SLOT(slot_cancelTool()));
    //connect(this,SIGNAL(sig_setTool(int)),dockView,SIGNAL(sig_setTool(int)));

    //connect(dockView,SIGNAL(sig_add_remove_spirit()),dockMapTree,SLOT(refresh()));
    //connect(dockView,SIGNAL(sig_add_remove_spirit()),dockProperty,SLOT(slot_shownull()));
    connect(dockView,SIGNAL(sig_chooseChanged(MapSpirit*)),dockMapTree,SLOT(slot_chooseChanged(MapSpirit*)));
    connect(dockView,SIGNAL(sig_chooseChanged(MapSpirit*)),dockProperty,SLOT(slot_showSpirit(MapSpirit*)));
    //connect(dockView,SIGNAL(sig_propertyChanged(MapSpirit*)),dockProperty,SLOT(slot_propertyChanged(MapSpirit*)));

    //属性窗口 修改 到 地图窗口的信号
    //    connect(dockProperty,SIGNAL(sig_propertyChanged(MapSpirit *)),dockView,SIGNAL(sig_propertyChangedFromProperty(MapSpirit*)));
    //    connect(dockProperty,SIGNAL(sig_propertyChanged(MapSpirit *)),dockMapTree,SLOT(refresh()));

    connect(blockView,SIGNAL(sig_chooseSpirit(MapSpirit*)),dockProperty,SLOT(slot_showSpirit(MapSpirit *)));

    connect(this,SIGNAL(sig_setSelectHand()),dockView,SIGNAL(sig_selectHand()));
    connect(this,SIGNAL(sig_setSelectSelect()),dockView,SIGNAL(sig_selectSelect()));
    connect(this,SIGNAL(sig_repaint()),dockView,SIGNAL(sig_repaint()));
    //connect(this,SIGNAL(sig_addBkg(int)),dockView,SLOT(slot_addBkg(int)));
}

void MainWindowFleet::loginControllerSucess_slot()
{
//    QTime dieTime = QTime::currentTime().addMSecs(2000);
//    while( QTime::currentTime() < dieTime )
//    {
//        QCoreApplication::processEvents(QEventLoop::AllEvents, 200);
//    }


    on_laodMapFile_triggered();

    emit loginControllerSucess_signal();
}

//void MainWindowFleet::controllerLogin_slot(QVector<int> controllerIpAddress, QVector<int> hmiIpAddress, QString port, QString passwardString, int selectedAccount)
//{
//    on_laodMapFile_triggered();
//}

void MainWindowFleet::updateMapShow_slot()
{
    dockMapTree->refresh();
    dockView->init();
}

void MainWindowFleet::onServerConnect()
{
    statusbar_info(QStringLiteral("已连接"));
}

void MainWindowFleet::onServerDisconnect()
{
    statusbar_info(QStringLiteral("连接已断开"));
}

void MainWindowFleet::onServerConnectting()
{
    statusbar_info(QStringLiteral("尝试连接服务器..."));
}

void MainWindowFleet::onSendFail()
{
    statusbar_err(QStringLiteral("发送请求失败"));
}

void MainWindowFleet::onWaitResponseTimeOut()
{
    statusbar_err(QStringLiteral("等待响应超时"));
}
void MainWindowFleet::onTip(QString s)
{
    statusbar_info(s);
}
void MainWindowFleet::onErr(int errcode,QString info)
{
    statusbar_err(getErrorString(errcode)+"  "+info);
}

void MainWindowFleet::onNewRequest()
{
    statusbar_err("");
    statusbar_info("");
}

void MainWindowFleet::updateCurrentUserInfo()
{
    usernamelabel->setText(QStringLiteral("当前用户:")+current_user_info.username);
    QString role_name = "";
    switch (current_user_info.role) {
    case USER_ROLE_VISITOR:
        role_name =QStringLiteral( "未登录");
        break;
    case USER_ROLE_OPERATOR:
        role_name =QStringLiteral( "普通用户");
        break;
    case USER_ROLE_ADMIN:
        role_name =QStringLiteral( "管理员");
        break;
    case USER_ROLE_SUPER_ADMIN:
        role_name =QStringLiteral( "超级管理员");
        break;
    case USER_ROLE_DEVELOP:
        role_name =QStringLiteral( "开发人员");
        break;
    default:
        break;
    }
    userrolelabel->setText(QStringLiteral("当前角色:")+role_name);
}


void MainWindowFleet::createStatusBar()
{
    statusbar = new QStatusBar(this);
    usernamelabel = new QLabel(QStringLiteral("当前用户:")+current_user_info.username);
    QString role_name = "";
    switch (current_user_info.role) {
    case USER_ROLE_VISITOR:
        role_name =QStringLiteral( "未登录");
        break;
    case USER_ROLE_OPERATOR:
        role_name =QStringLiteral( "普通用户");
        break;
    case USER_ROLE_ADMIN:
        role_name =QStringLiteral( "管理员");
        break;
    case USER_ROLE_SUPER_ADMIN:
        role_name =QStringLiteral( "超级管理员");
        break;
    case USER_ROLE_DEVELOP:
        role_name =QStringLiteral( "开发人员");
        break;
    default:
        break;
    }
    userrolelabel = new QLabel(QStringLiteral("当前角色:")+role_name);
    info_label = new QLabel(QStringLiteral("信息:"));
    error_label = new QLabel(QStringLiteral("错误:"));
    usernamelabel->setMinimumWidth(200);
    userrolelabel->setMinimumWidth(200);
    info_label->setMinimumWidth(200);

    statusbar->addWidget(usernamelabel);
    statusbar->addWidget(userrolelabel);
    statusbar->addWidget(info_label);
    statusbar->addWidget(error_label);

    setStatusBar(statusbar);
}

void MainWindowFleet::createActions()
{
    QMenu *viewsMenu = menuBar()->addMenu(tr("视图"));
    QToolBar *viewsToolBar = addToolBar(tr("Views"));

    dock_user_manage = new DockUserManage();
    addDockWidget(Qt::RightDockWidgetArea, dock_user_manage);
    viewsMenu->addAction(dock_user_manage->toggleViewAction());
//    viewsToolBar->addAction(dock_user_manage->toggleViewAction());
    dock_agv_manage = new DockAgvManage();
    addDockWidget(Qt::RightDockWidgetArea, dock_agv_manage);
    viewsMenu->addAction(dock_agv_manage->toggleViewAction());
//    viewsToolBar->addAction(dock_agv_manage->toggleViewAction());
    dock_user_log = new DockUserLog();
    addDockWidget(Qt::RightDockWidgetArea,dock_user_log);
    viewsMenu->addAction(dock_user_log->toggleViewAction());
//    viewsToolBar->addAction(dock_user_log->toggleViewAction());
    dock_device_log = new DockDevice();
    addDockWidget(Qt::RightDockWidgetArea,dock_device_log);
    viewsMenu->addAction(dock_device_log->toggleViewAction());
//    viewsToolBar->addAction(dock_device_log->toggleViewAction());
    dock_task = new DockTask();
    addDockWidget(Qt::LeftDockWidgetArea,dock_task);
    viewsMenu->addAction(dock_task->toggleViewAction());
//    viewsToolBar->addAction(dock_task->toggleViewAction());

    dock_user_manage->hide();
    dock_agv_manage->hide();
    dock_user_log->hide();
    dock_device_log->hide();
    dock_task->hide();

    action_map_edit = new QAction("地图编辑", this);
    action_map_edit->setCheckable(true);
    viewsMenu->addAction(action_map_edit);
    viewsToolBar->addAction(action_map_edit);

    action_fleet_test = new QAction("调度测试", this);
    action_fleet_test->setCheckable(true);
    viewsMenu->addAction(action_fleet_test);
    viewsToolBar->addAction(action_fleet_test);

    action_loadMapFile = new QAction("加载地图文件", this);
    action_loadMapFile->setCheckable(false);
    viewsMenu->addAction(action_loadMapFile);
    viewsToolBar->addAction(action_loadMapFile);

    connect(action_map_edit,SIGNAL(triggered(bool)),this,SLOT(onMapEdit(bool)));
    connect(action_fleet_test,SIGNAL(triggered(bool)),this,SLOT(on_fleetTest_triggered(bool)));
    connect(action_loadMapFile,SIGNAL(triggered(bool)),this,SLOT(on_laodMapFile_triggered()));

    QMenu *helpMenu = menuBar()->addMenu(tr("帮助"));
    QAction *aboutAct = helpMenu->addAction(tr("&About"));
    aboutAct->setStatusTip(tr("Show the application's About box"));

    QAction *aboutQtAct = helpMenu->addAction(tr("About &HY"));
    aboutQtAct->setStatusTip(tr("Show the HY's About box"));

    //////////////////////////////////新增加

    dockMapTree = new MonitorDockMapTree(oneMap);
    dockProperty = new MonitorDockProperty(oneMap);
    dockView = new MonitorDockView(oneMap);
    blockView = new MonitorDockBlock(oneMap);
    blockView->hide();

    addDockWidget(Qt::LeftDockWidgetArea,dockMapTree);
    addDockWidget(Qt::LeftDockWidgetArea,dockProperty);
    //    addDockWidget(Qt::RightDockWidgetArea,dockView);
    tabifyDockWidget(dockMapTree,blockView);

    addDockWidget(Qt::LeftDockWidgetArea,dockMapTree);
    addDockWidget(Qt::LeftDockWidgetArea,dockProperty);
    addDockWidget(Qt::RightDockWidgetArea,dockView);
    tabifyDockWidget(dockMapTree,blockView);

    setCentralWidget(dockView);

    QToolBar *selectToolBar = addToolBar(tr("Selects"));

    selectSelect = new QAction(this);
    selectSelect->setText("选择");
    selectSelect->setObjectName("selectSelect");
    selectSelect->setCheckable(true);
    selectToolBar->addAction(selectSelect);

    selectHandNew = new QAction(this);
    selectHandNew->setText("拖动");
    selectHandNew->setObjectName("selectHandNew");
    selectHandNew->setCheckable(true);//
    selectToolBar->addAction(selectHandNew);

    selectDisplayItemRatioIncrease = new QAction(this);
    selectDisplayItemRatioIncrease->setText("放大");
    selectDisplayItemRatioIncrease->setObjectName("displayItemRatioIncrease");
//    QIcon iconSelectHand;
//    iconSelectHand.addFile(":/images/toolbar/point-report.22.png",QSize(),QIcon::Normal,QIcon::Off);
//    selectHand->setIcon(iconSelectHand);
    selectDisplayItemRatioIncrease->setCheckable(false);
    selectToolBar->addAction(selectDisplayItemRatioIncrease);


    selectDisplayItemRatioDecrease = new QAction(this);
    selectDisplayItemRatioDecrease->setText("缩小");
    selectDisplayItemRatioDecrease->setObjectName("displayItemRatioDecrease");
//    QIcon iconSelectHand;
//    iconSelectHand.addFile(":/images/toolbar/point-report.22.png",QSize(),QIcon::Normal,QIcon::Off);
//    selectHand->setIcon(iconSelectHand);
    selectDisplayItemRatioDecrease->setCheckable(false);
    selectToolBar->addAction(selectDisplayItemRatioDecrease);

    viewsMenu->addAction(dockMapTree->toggleViewAction());
//    viewsToolBar->addAction(dockMapTree->toggleViewAction());

    viewsMenu->addAction(dockProperty->toggleViewAction());
//    viewsToolBar->addAction(dockProperty->toggleViewAction());

    viewsMenu->addAction(blockView->toggleViewAction());
//    viewsToolBar->addAction(blockView->toggleViewAction());

    viewsMenu->addAction(dockView->toggleViewAction());
//    viewsToolBar->addAction(dockView->toggleViewAction());

    viewsMenu->addAction(blockView->toggleViewAction());
//    viewsToolBar->addAction(blockView->toggleViewAction());

//    viewsMenu->addAction(dockView->toggleViewAction());
//    viewsToolBar->addAction(dockView->toggleViewAction());

    connect(selectDisplayItemRatioIncrease,SIGNAL(triggered(bool)),this,SLOT(on_displayItemRatioIncrease_triggered(bool)));
    connect(selectDisplayItemRatioDecrease,SIGNAL(triggered(bool)),this,SLOT(on_displayItemRatioDecrease_triggered(bool)));
    connect(selectSelect,SIGNAL(triggered(bool)),this,SLOT(on_selectSelect_triggered(bool)));
    connect(selectHandNew,SIGNAL(triggered(bool)),this,SLOT(on_selectHandNew_triggered(bool)));

}

void MainWindowFleet::about()
{
    QMessageBox::about(this, tr("About Application"),
                       tr("welcom"));
}

void MainWindowFleet::aboutHY()
{
    QMessageBox::about(this, tr("About Hit Robot Group"),
                       tr("welcom"));
}

void MainWindowFleet::statusbar_info(QString msg)
{
    info_label->setText(QStringLiteral("信息:")+msg);
}

void MainWindowFleet::statusbar_err(QString msg)
{
    error_label->setText(QStringLiteral("错误:")+msg);
}

void MainWindowFleet::onMapEdit(bool b)
{
    if(b)
    {
        if(editWindow)
        {
//            editWindow->close();
//            delete editWindow;
            editWindow->move(80,80);

           editWindow->show();

        }
        else
        {
            static int tmpCount=0;
            editWindow = new MapEditWindow(communicateNormal,globalData,g_onemap.clone());
            editWindow->show();
            if(0==tmpCount)
            {
                g_windowShowManage->addWindow(editWindow,"路径地图编辑");
                tmpCount++;
            }
            QObject::connect(this,SIGNAL(loginControllerSucess_signal()),
                             editWindow,SLOT(loginControllerSucess_slot() ) );

        }

    }
    else
    {
        editWindow->hide();
        dockView->init();
    }


}

void MainWindowFleet::on_fleetTest_triggered(bool b)
{
    if(b)
    {
//        fleetTestWindow->show();／
        fleetTestManagementWindow->move(1200,20);
        fleetTestManagementWindow->show();
        static int tmpCount=0;
        if(0==tmpCount)
        {
            g_windowShowManage->addWindow(fleetTestManagementWindow,"调度测试");
            tmpCount++;
        }
    }
    else
    {
//        fleetTestWindow->hide();
        fleetTestManagementWindow->hide();
    }
}

void MainWindowFleet::on_laodMapFile_triggered()
{
    switch(msgCenter.getLoginMode())
    {
    case E_LOGIN_MODE_OFFLINE:
    {
        //定义文件对话框类
       QFileDialog *fileDialog = new QFileDialog(this);
       fileDialog->resize(400,500);
       //定义文件对话框标题
       fileDialog->setWindowTitle(tr("选择文件"));
       //设置默认文件路径
       QString configFile=D_MAP_FILE_PATH;

       fileDialog->setDirectory(configFile);
       //设置文件过滤器
       fileDialog->setNameFilter(tr("json(*.mjson)"));
       //设置可以选择多个文件,默认为只能选择一个文件QFileDialog::ExistingFiles
       fileDialog->setFileMode(QFileDialog::ExistingFiles);
       //设置视图模式
       fileDialog->setViewMode(QFileDialog::Detail);
       //打印所有选择的文件的路径
       QStringList fileNames;
       if(fileDialog->exec())
       {
           fileNames = fileDialog->selectedFiles();
       }
        qDebug()<<fileNames;
        if(fileNames.size()>0)
        {

            QString filePath =fileNames[0];
            MapFileParse mapfileParser;
            mapfileParser.loadMapFromFile(true,filePath,oneMap);

            if(oneMap->getDisplayRatio()>0 && oneMap->getDisplayRatio()<1000)
            {
                 g_itemDisplayRatio=oneMap->getDisplayRatio();
            }
            dockMapTree->refresh();
            dockView->init();

            QFileInfo file_info(filePath);
            QString tmpNote="本地地图版本:";
            tmpNote+=QString::number(oneMap->getVersion())+" 最后编辑:"
                    +file_info.lastModified().toString("yyyy-MM-dd hh:mm:ss");
            QMessageBox::information(this,QStringLiteral("监视:地图加载成功"),tmpNote);
        }


        break;
    }
    case E_LOGIN_MODE_MONITOR:
    {
        MapFileParse mapfileParser;
        std::string mapInfoReturn;
        communicateNormal->getFleetMap("",mapInfoReturn);
        if(""==mapInfoReturn)
        {
            QMessageBox::information(this,QStringLiteral("提示"),"地图为空,加载失败");
            oneMap->clear();
            updateMapShow_slot();
        }
        else
        {
            mapfileParser.transStringToMap(true,mapInfoReturn,oneMap);

            if(oneMap->getDisplayRatio()>0 && oneMap->getDisplayRatio()<1000)
            {
                 g_itemDisplayRatio=oneMap->getDisplayRatio();
            }

            updateMapShow_slot();

            QString tmpNote="远程地图版本:";
            tmpNote+=QString::number(oneMap->getVersion());
            QMessageBox::information(this,QStringLiteral("监视:地图加载成功"),tmpNote);
        }

        break;
    }
    case E_LOGIN_MODE_DISPATCH:
    {
        break;
    }
    }

}

void MainWindowFleet::onMapLoad()
{
    oneMap = g_onemap.clone();
    //TODO:重新载入
}


void MainWindowFleet::on_selectSelect_triggered(bool b)
{
    selectHandNew->setChecked(false);
    emit sig_setSelectSelect();
}

void MainWindowFleet::on_selectHandNew_triggered(bool b)
{
    if(b){
        selectSelect->setChecked(false);
        emit sig_setSelectHand();
    }
    else
        emit sig_setSelectSelect();
}

void MainWindowFleet::on_displayItemRatioIncrease_triggered(bool b)
{
    g_itemDisplayRatio+=0.2;
    qDebug()<<"displayItemRatioIncrease g_itemDisplayRatio"<<g_itemDisplayRatio;
//    paintingActive();
//    emit paintEvent();
//    repaint();
    emit sig_repaint();
}

void MainWindowFleet::on_displayItemRatioDecrease_triggered(bool b)
{

    g_itemDisplayRatio-=0.2;
    if(g_itemDisplayRatio<0)
    {
        g_itemDisplayRatio=0.1;
    }
    qDebug()<<"displayItemRatioDecrease g_itemDisplayRatio"<<g_itemDisplayRatio;
//    paintingActive();
//    repaint();
    emit sig_repaint();
}
